package com.itheima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.PageVo;
import com.itheima.admin.dto.DeptDto;
import com.itheima.admin.dto.UserRoleDto;
import com.itheima.admin.mapper.DeptMapper;
import com.itheima.admin.pojo.Dept;
import com.itheima.admin.service.IDeptService;
import com.itheima.admin.vo.DeptPageVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DeptServiceImpl implements IDeptService {

    @Autowired
    private DeptMapper deptMapper;


    @Override
    public PageVo<DeptPageVo> queryByPage(DeptDto deptDto) {
        IPage<Dept> page =new Page<>(deptDto.getCurrentPage(),deptDto.getPageSize());
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(deptDto.getDeptName()!=null,"dept_name",deptDto.getDeptName());
        queryWrapper.like(deptDto.getStatus()!=null,"state",deptDto.getStatus());
        IPage<Dept> deptIPage = deptMapper.selectPage(page, queryWrapper);
        List<DeptPageVo> collect = deptIPage.getRecords().stream().map(
                dept -> {
                    DeptPageVo deptPageVo = new DeptPageVo();
                    BeanUtils.copyProperties(dept, deptPageVo);
                    return deptPageVo;
                }
        ).collect(Collectors.toList());
        return new PageVo<DeptPageVo>(collect,(int)deptIPage.getTotal());
    }

    public List<Dept> selectAll(){
        List<Dept> depts = deptMapper.selectList(null);
        return depts;
    }

    public boolean insertDept(Dept dept){
        int insert = deptMapper.insert(dept);
        if (insert>0){
            return true;
        }
        else{
            return false;
        }
    }
    public boolean deleteDeptById(String id){
        int i = deptMapper.deleteById(id);
        if (i>0){
            return true;
        }
        else {
            return false;
        }
    }

    public Dept selectDeptById(int id){
        Dept dept = deptMapper.selectById(id);
        return dept;
    }

    @Override
    public boolean updateDept(Dept dept) {
        int result = deptMapper.updateById(dept);
        return result>0;
    }
}
